package models

import (
	"strconv"
	"strings"
	"time"
)

const TimeFormat = "2006-01-02T15:04:05"

type LocalTime time.Time

func (t *LocalTime) UnmarshalJSON(data []byte) (err error) {
	// 空值不进行解析
	if len(data) == 2 {
		*t = LocalTime(time.Time{})
		return
	}
	s := string(data)
	if len(data) == 13 {
		i, err := strconv.ParseInt(s, 10, 64)
		if err != nil {
			return nil
		}
		s = time.Unix(i/1000, 0).Format(TimeFormat)
		s = `"` + s + `"`
	}

	// 指定解析的格式
	now, err := time.Parse(`"`+TimeFormat+`"`, s)
	*t = LocalTime(now)
	return
}

func (t LocalTime) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(TimeFormat)+2)
	b = append(b, '"')
	b = time.Time(t).AppendFormat(b, TimeFormat)
	b = append(b, '"')
	return b, nil
}

type LocalInt64 int64

func (t *LocalInt64) UnmarshalJSON(data []byte) (err error) {
	s := strings.Trim(string(data), "\"")
	intNum, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		return err
	}
	*t = LocalInt64(intNum)
	return nil
}

// MarshalJSON 这里需要手动加上引号，不会自动生成
func (t *LocalInt64) MarshalJSON() ([]byte, error) {
	return ([]byte)("\"" + strconv.FormatInt(int64(*t), 10) + "\""), nil
}
